package com.yfbao.horizon.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JdbcUtils_druid {

    //4.提升作用域
    private static DataSource dataSource = null;

    //1.获取数据源 dataSource
    static {
        try {
            Properties prop = new Properties();
            // 读取配置文件
            InputStream is = JdbcUtils.class.getResourceAsStream("/druid.properties");
            try {
                prop.load(is);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {//返回的是
                dataSource = DruidDataSourceFactory.createDataSource(prop);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //2.获取连接 (数据源dataSource自带连接)
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    //3.释放连接资源
    public static void release(Connection connection, Statement statement, ResultSet resultSet){
        if(resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(statement != null){
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(connection != null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}


